#include "GameEngine.h"
#include "Scene\SceneManager.h"
#include "Graphics\RendererOpenGL.h"
#include "Audio\AudioManager.h"
#include "GUI\GUIManager.h"
#include <time.h>
#include <iostream>
#include <algorithm>


GameEngine* GameEngine::_instance = NULL;

GameEngine::GameEngine(WNDPROC WndProc) {
	//Whenever want to switch between Directx or OpenGL
	//Just comment out one of the following that you do not want to use
	_renderer = new RendererOpenGL(WndProc);
	//Renderer *renderer = new RendererDirectX((WNDPROC) WndProc);

	SceneManager::create();
	AudioManager::create();
	GUIManager::create();

	_state = MENU;	
}

GameEngine* GameEngine::Instance () {
	return _instance;
}

GameEngine::~GameEngine() {
	SceneManager::destroy();
	AudioManager::destroy();
	GUIManager::destroy();
	_instance = NULL;
}

void GameEngine::ResizeWindow(int width, int height) {
	// Resize the window
	_renderer->ReSizeScene(width,height);
}

void GameEngine::Update() {		
	switch(_state) {
	case PLAY: 
		SceneManager::Instance()->updateScene();
		break; 
	case PAUSE: {
		COLOR color = {1,0,0};
		this->getRenderer()->writeOnScreen("GAME PAUSED", 0,-13,18,color);
		//SceneManager::Instance()->renderScene();
		break;
	}
	case GAMEOVER:
		break;
	case MENU:
		GUIManager::Instance()->displayGameMenu();
	}
}

void GameEngine::Draw() {
	_renderer->startDrawingScene();
	switch(_state) {
	case PLAY:
		SceneManager::Instance()->renderScene();
		break;
	case PAUSE:
		SceneManager::Instance()->renderScene();
		break; 
	case GAMEOVER:
		break;
	case MENU:
		GUIManager::Instance()->displayGameMenu();
	}	
	_renderer->stopDrawingScene();	
}

void GameEngine::ToggleFullScreenMode() {
	// Toggle between fullscreen and window mode
	_renderer->ToggleFullScreenMode();
}

void GameEngine::CloseWindow() {
	// Close the rendering window
	_renderer->KillWindow();
}

bool GameEngine::Initialize() {
	
	// Initialize the engine, i.e. for now create the window

	return _renderer->CreateAWindow();
}

Renderer * GameEngine::getRenderer() const
{
	return _renderer;
}

state GameEngine::getGameState()
{
	return _state;
}

void GameEngine::setGameState(state a)
{
	_state = a;
}

void GameEngine::onKeyPressed(int key)
{
	if(key == 'M' || key == 'm')
		setGameState(MENU);
	if(key == 'P' || key == 'p')
	{
		if(getGameState() != MENU) {
			setGameState((getGameState()==PLAY) ? PAUSE : PLAY);
		}
	}
	if(key == 'ESC')
	{
		setGameState(GAMEOVER);
	}
}
void GameEngine::onKeyReleased(int key){}